/**
 * 
 */
package vo;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

/**
 * @author Saulo
 *
 */
public class ItemEstoqueDAO {
	
	//SALVAR ITEM ESTOQUE
	public void salvarItemEstoque(ItemEstoqueVO itemEstoque) {

		Transaction transaction = null;

		Session session = HibernateUtil.currentSession();
		transaction = session.beginTransaction();

		session.saveOrUpdate(itemEstoque);

		transaction.commit();

	}
	
	public void salvarItemEstoqueZero(ItemEstoqueVO itemEstoque, Session session) {
		session.saveOrUpdate(itemEstoque);
	}
			
			//EXCLUIR ITEM ESTOQUE
			public void excluir(Integer idItEst) {
				Transaction transaction = null;
				
				ItemEstoqueVO itemEstoque = obter(idItEst);

				Session session = HibernateUtil.currentSession();
				transaction = session.beginTransaction();

				session.delete(itemEstoque);

				transaction.commit();
			}
			
			//OBTER ITEM ESTOQUE
			public ItemEstoqueVO obter(Integer idItEst) {
				Transaction transaction = null;

				Session session = HibernateUtil.currentSession();
				transaction = session.beginTransaction();

				Criteria criteria = session.createCriteria(ItemEstoqueVO.class);
				criteria.add(Restrictions.eq("idItEst", idItEst));

				ItemEstoqueVO itemEstoque = (ItemEstoqueVO) criteria.uniqueResult();

				transaction.commit();

				return itemEstoque;
			}

			@SuppressWarnings("unchecked")
			public List<ItemEstoqueVO> consultarItensEstoque() {
				
				Transaction transaction = null;
				
				Session session = HibernateUtil.currentSession();
				transaction = session.beginTransaction();
				
				Criteria criteria = session.createCriteria(ItemEstoqueVO.class);
				
				List<ItemEstoqueVO> itemEstoque = criteria.list();
				
				List<ItemEstoqueVO> listaItemEstoqueAuxiliar = new ArrayList<ItemEstoqueVO>();
				ProdutoDAO dao = new ProdutoDAO();
				ItemEstoqueVO vo = new ItemEstoqueVO();
				
				for(ItemEstoqueVO itVO : itemEstoque){
					itVO.setProdutoVO(dao.consultarProdutoPorId(itVO.getProdutoIdProd(), session));
					vo = itVO;
					listaItemEstoqueAuxiliar.add(vo);
					vo = new ItemEstoqueVO();
					
				}
				
				
				
				transaction.commit();
				
				
				return listaItemEstoqueAuxiliar;
			}
			
			public int consultarItensEstoquePorIdProduto(int id) {
				
				Transaction transaction = null;
				
				Session session = HibernateUtil.currentSession();
				transaction = session.beginTransaction();
				
				Criteria criteria = session.createCriteria(ItemEstoqueVO.class).add(Restrictions.eq("produtoIdProd", id));
				
				ItemEstoqueVO itemEstoque = (ItemEstoqueVO) criteria.uniqueResult();
				
				transaction.commit();
				
				return itemEstoque.getQuantItEst();
			}

}
